import {
	REDIRECT_PATH
} from '@/config/constant'
import {
	HOME_PAGE_PATH
} from '@/config/index'
import {
	last
} from './util.js'

import {
	convertObj2Str
} from './util.js'

import {
	setCache,
	getCache
} from './storage'

import store from '@/store'

/**
 * 获取当前路由
 */
export function currentRoute() {
	let { route, options } = last(getCurrentPages())
	//拼接路径，把参数也带着
	return makeUrl(route, options)
}

/**
 * 拼接URL,避免拼接字符串
 * @param {String} url
 * @param {Object} args
 */
export function makeUrl(url, args) {
	if (!args) return url
	let params = convertObj2Str(args)
	if (!params) return url
	return [url, params].join('?')
}

/**
 * 跳转页面
 */
export function $go2(url, isTab = false, isRedirect = false) {
	uni[isTab ? 'switchTab' : isRedirect ? 'redirectTo' : 'navigateTo']({ url })
}

/**
 * 拦截，重定向到登录页
 */
export function $redirect2Login(fromPath = '') {
	if (!fromPath) fromPath = '/' + currentRoute()
	setCache(REDIRECT_PATH, fromPath)

	// #ifdef MP-WEIXIN
	$go2(`/pages/main/account/wx-intro`, false, true)
	// #endif
	// #ifndef MP-WEIXIN
	$go2(`/pages/main/account/phone-login`, false, true)
	// #endif
}

/**
 * 登录后跳转
 * 跳转回去或者到首页
 */
export function $redirectAfterLogin() {
	// 是否有被拦截的来源页面
	let redirect = getCache(REDIRECT_PATH)
	if (['/pages/main/account/wx-intro', '/pages/main/account/phone-login'].includes(redirect))
		redirect = HOME_PAGE_PATH
	//如果是tabbar里面的页面， 需要switchTab，所以需要第二个参数
	console.log(redirect);
	let isTab = [
		'/pages/main/tabbar/index/index',
		'/pages/main/tabbar/category/category',
		'/pages/main/tabbar/cart/cart',
		'/pages/main/tabbar/message/list',
		'/pages/main/tabbar/mine/mine'
	].includes(redirect || HOME_PAGE_PATH)
	//从登录跳转的话，需要redirect
	$go2(redirect, isTab, true)
}

/**
 * 返回
 */
export const $back = () => uni.navigateBack()
